package com.yk.airline.dao.common.impl;


import com.yk.airline.dao.common.api.IComSearchDao;
import com.yk.airline.dao.common.api.ICommonDao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;


/**
 * Created by Satani on 2017/5/17.
 */
@Repository("commonDao")
public class CommonDaoImpl<T> implements ICommonDao<T> {

    @Autowired
    private SessionFactory sessionFactory;
    @Resource(name = "comSearchDao")
    protected IComSearchDao<T> comSearchDao;

    private Class<T> entity;

    public CommonDaoImpl(){
        Type type = this.getClass().getGenericSuperclass();
        if(type instanceof ParameterizedType){
            Type[] types = ((ParameterizedType) type).getActualTypeArguments();
            entity = (Class<T>) types[0];
        }
    }

    /**
     * 添加
     *
     * @param object 实体对象
     * @return 添加状态，true：成功，false：失败
     */

    @Override
    public Serializable save(T object) {
        Serializable result = null;
        try {
             result = sessionFactory.getCurrentSession().save(object);
        }catch (Exception e ){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 删除
     *
     * @param object 实体对象
     * @return 删除状态，true：成功，false：失败
     */
    @Override
    public boolean delete(T object) {
        boolean flag = true ;
        try {
            sessionFactory.getCurrentSession().delete(object);
        }catch (Exception e ){
            flag =false ;
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 更新
     *
     * @param object 实体对象
     * @return 更新状态，true：成功，false：失败
     */
    @Override
    public boolean update(T object) {
        boolean flag = true ;
        try {
            sessionFactory.getCurrentSession().update(object);
        }catch (Exception e ){
            flag =false ;
            e.printStackTrace();
        }
        return flag;
    }


}
